<template>
    <el-tree
        ref="menuTree"
        :data="menuList"
        show-checkbox="true"
        node-key="id"
        default-expand-all
        :props="defaultProps"
    ></el-tree>
    <el-button @click="onAuthMenu">确定</el-button>
</template>

<script setup lang="ts">
import { ref, type Ref, onMounted } from 'vue'
import { ElTree } from 'element-plus'
import type { IMenu } from '@/utils/types'
import { RequestMenu, RequestAuthorRole } from '@/api/index'
const menuList = ref<Array<Tree>>([])
const selectMenuList = ref<Array<Tree>>([])
const menuTree = ref()
interface Tree {
    id: number
    label: string
    children?: Tree[]
}
// 定义树形菜单节点属性
const defaultProps = {
    children: 'children',
    label: 'label',
}
const props = defineProps({
    roleId: Number,
})
onMounted(() => {
    getMenuList()
})

/**
 * 所有权限列表
 */
const getMenuList = async () => {
    const rootRoleId = 1 //超级管理员roleId:1,返回所有菜单数据
    const data = await RequestMenu(rootRoleId)
    const { resultCode, resultInfo } = data
    if (resultCode === 1) {
        menuList.value = resultInfo

        setSelectorMenuList()
    }
}

/**
 * 当前角色菜单权限
 */
const setSelectorMenuList = () => {
    const currentRoleId: Number = props.roleId //当前角色Id

    RequestMenu(currentRoleId).then(data => {
        let { resultCode, resultInfo } = data
        if (resultCode == 1) {
            selectMenuList.value = resultInfo
            menuTree.value.setCheckedNodes(resultInfo)
        }
    })
}

/**
 * 设置菜单权限
 */
const onAuthMenu = async () => {
    const resType: number = 0 //resType: 0菜单资源, 2按钮资源
    const roleId: number = props.roleId //当前角色Id
    let nodes = menuTree.value.getCheckedNodes()
    nodes = nodes.map(item=>item.id)
    console.log(nodes)
    const ids: string = nodes.join(',')
    console.log('ids ', ids)
    const data = await RequestAuthorRole(roleId, ids, resType)
    let { resultCode, resultInfo } = data

    if (resultCode == 1) {
        ElMessage.success('设置权限成功!')
    }
}
</script>

<style scoped></style>
